package cn.itsource.pethome.web.controller;

import cn.itsource.pethome.utils.AjaxResult;
import cn.itsource.pethome.utils.FastDfsUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/fastdfs")
public class FastdfsController {

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(MultipartFile file){
        try {
            String filename = file.getOriginalFilename();
            //获取后缀名称
            String extName = filename.substring(filename.lastIndexOf(".") + 1);
            //调用工具类方法
            String savePath = FastDfsUtils.upload(file.getBytes(), extName);
            return AjaxResult.me().setData(savePath);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("上传失败！" + e.getMessage());
        }
    }

    /**
     * 删除fastdfs服务器上面的文件
     * @param filePath
     * @return
     */
    @DeleteMapping("/deleteFile")
    public AjaxResult deleteFile(String filePath){
        try {
            //去掉第一个斜杠
            filePath = filePath.substring(1);
            //  group1
            String groupName = filePath.substring(0, filePath.indexOf("/"));
            //  M00/01/03/wKgABF_i-qKAU55lAABOn9tJHQU055.jpg
            String fileName = filePath.substring(filePath.indexOf("/") + 1);
            System.out.println(groupName);
            System.out.println(fileName);
            //调用工具类方法删除fastdfs服务器上面的文件  文件删除需要清除浏览器缓存 再次访问图片就会404了
            FastDfsUtils.delete(groupName, fileName);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("文件删除失败！" + e.getMessage());
        }
    }

}
